<?php
// +----------------------------------------------------------------------
// | Description: 产品
// +----------------------------------------------------------------------
// | Author:  Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------
namespace app\crm\model;

use think\Db;
use app\admin\model\Common;
use think\Request;
use think\Validate;

class Confirmation extends Common
{
	/**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
	protected $name = 'crm_confirmation';
    protected $createTime = '';
    protected $updateTime = '';
	protected $autoWriteTimestamp = true;

	/**
     * [getDataList 确认函list]
     * @author 
     * @param     [string]                   $map [查询条件]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [每页数量]
     * @return    [array]                    [description]
     */		
	public function getDataList($request)
    {
        $search = $request['search'];
        $where['title'] = ['like', '%'.$search.'%'];
        $list=$this->where($where)
            ->limit(($request['page']-1)*$request['limit'], $request['limit'])
            ->select();
        $dataCount=$this->where($where)->count();
        $data = [];
        $data['list'] = $list;
        $data['dataCount'] = $dataCount ? : 0;
        return $data;
    }
    public function getList()
    {
        $list = $this->field("confirmation_id type_id,title name,remark")->order('confirmation_id desc')->select();
        return $list ? : [];
    }
    /**
     * 创建确认函
     * @author
     * @param
     * @return
     */
    public function createData($param)
    {
        /*$model=model("Contract");
        $res=$model->getOkStatus($param["contract_id"]);
        if($res!=true)
        {
            $this->error = '添加失败';
            return false;
        }*/
        if ($this->data($param)->allowField(true)->isUpdate(false)->save()) {
            //修改记录
            //updateActionLog($param['create_user_id'], 'crm_confirmation', $this->customer_id, '', '', '创建了确认函');
            $data = [];
            $data['title'] = $param['title'];
            return $data;
        } else {
            $this->error = '添加失败';
            return false;
        }
    }
    /**
     * 确认函详情
     * @param  $id 确认函ID
     * @return
     */
    public function getDataById($confirmation_id = '')
    {
        $map['confirmation_id'] = $confirmation_id;
        $dataInfo = $this->where($map)->find();
        if (!$dataInfo) {
            $this->error = '数据不存在或已删除';
            return false;
        }
        $model=model("ConfirmationCategory");
        $dataInfo["category"]=$model->getListById($confirmation_id);
        return $dataInfo;
    }

    /**
     * 编辑确认函信息
     * @author Michael_xu
     * @param
     * @return
     */
    public function updateDataById($param, $confirmation_id = '')
    {
        //$user_id = $param['user_id'];
        $dataInfo = $this->get($confirmation_id);
        if (!$dataInfo) {
            $this->error = '数据不存在或已删除';
            return false;
        }
        if ($this->allowField(true)->save($param, ['confirmation_id' => $confirmation_id])) {
            //修改记录
            //updateActionLog($user_id, 'crm_customer', $confirmation_id, $dataInfo->data, $param);
            $data = [];
            $data['confirmation_id'] = $confirmation_id;
            return $data;
        } else {
            $this->error = '编辑失败';
            return false;
        }
    }
    /**
     * 删除确认函
     * */
    public function del($confirmation_id)
    {
        /*$model=model("Contract");
        $res=$model->getOkStatus($confirmation_id);
        if($res!=true)
        {
            $this->error = '添加失败';
            return false;
        }*/
        $map['confirmation_id'] = $confirmation_id;
        $dataInfo = $this->where($map)->find();
        if (!$dataInfo) {
            $this->error = '数据不存在或已删除';
            return false;
        }
        $this->startTrans();
        try {
            $dataInfo->delete();
            ConfirmationCategory::where(["confirmation_id"=>$confirmation_id])->delete();
            return true;
        } catch(\Exception $e) {
            $this->rollback();
            $this->error = '添加失败';
            return false;
        }
    }
    /**
     * 根据合同选中产品查找绑定确认函
     * */
    public function getDataByCheckedId($product_id,$contract_id=0)
    {

       $product=Product::field("confirmation_id")->where(["product_id"=>$product_id])->find();
       if(empty($product)){
           $this->error = '该产品不存在';
           return false;
       }

        $where["confirmation_id"]=$product["confirmation_id"];
        $list = $this->field("confirmation_id,title,remark")
            ->where($where)
            ->find();

       if(!empty($list)){
           $categoryWhere["confirmation_id"]=$product["confirmation_id"];
           if($contract_id=="0"){
               $categoryWhere["title"]=["not in",["服务期数","记账单量","订单类型","原销售"]];
           }
           //不能合同绑定后的确认函修改的字段
           $category=ConfirmationCategory::where($categoryWhere)
               ->order("weight","asc")->select();
           if(!empty($category)){
               foreach ($category as &$v){
                   $v["config"]=json_decode($v["config"],true);
                   $v["value"]='';
                   $v["contract_confirmation_id"]='';
                    if (!empty($contract_id)){
                        $values=ContractConfirmation::field("value_data,contract_confirmation_id")
                            ->where(['confirmation_category_id'=>$v["confirmation_category_id"],"contract_id"=>$contract_id,"product_id"=>$product_id,"confirmation_id"=>$v["confirmation_id"]])
                            ->find();
                        if(!empty($values)){
                            $v["value"]=json_decode($values["value_data"],true);
                            $v["contract_confirmation_id"]=$values["contract_confirmation_id"];
                        }
                    }
               }
           }
           $list["category"]=$category;
       }
       return $list ? : [];
    }
}
